#include "pch.h"

#include "iosystem/textreader.h"



namespace IO
{

	///
	TextReader::TextReader()
	{

	}


	///
	TextReader::~TextReader()
	{

	}



	///
	uchar TextReader::ReadChar()
	{
		uchar c;

		this->m_stream->Read(&c, sizeof(c));

		return c;
	}


	///
	Helper::String TextReader::ReadLine()
	{
		Helper::String result;

		const int size = 128;

		char * buffer = (char*)Memory::MemoryManager::Alloc(Memory::ScratchHeap, size);

		bool newLine = false;

		while(!(newLine || this->m_stream->Eof()))
		{
			int readBytes = this->m_stream->Read(buffer, size - 1);

			buffer[readBytes] = 0;

			char * pNewLine = strchr(buffer, '\n');

			if(pNewLine)
			{
				*pNewLine = 0;

				newLine = true;

				int newLinePos = (int)(pNewLine - buffer);
				int offset = (newLinePos - readBytes) + 1;
				this->m_stream->Seek(offset, Stream::Current);
			}

			result.Add(buffer);
		}

		Memory::MemoryManager::Free(Memory::ScratchHeap, buffer);

		return result;
	}


	///
	Helper::Array<Helper::String> TextReader::ReadAllLines()
	{
		Helper::Array<Helper::String> result;

		while(!this->m_stream->Eof())
			result.Add(this->ReadLine());

		return result;
	}

}